package com.itheima.controller;

import com.itheima.config.ShortMessageProperties;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.JedisPool;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 吴
 * @version V1.0
 * @Description  发送短信控制器
 * @Package com.itheima.controller
 * @date 2021/11/26 20:46
 */
@RestController
@RequestMapping("/sms")
public class ShortMessageSendController {

    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private ShortMessageProperties message;
    /**
     * 发送预约验证短信
     * @param telephone 手机号
     * @return
     */
    @GetMapping("/sendCode/{telephone}")
    public Result sendCode(@PathVariable("telephone") String telephone){

        // 匹配手机号
        String regExp="^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Matcher m = Pattern.compile(regExp).matcher(telephone);
        if(m.matches() == false){
            return new Result(false,"请输入正确的手机号码");
        }
        // 发送短信
        Result result =  result = SMSUtils.sendCodeByShortMessage(message.getHost(), message.getPath(), message.getAppcode(), message.getSkin(), telephone);

        // 取出验证码
        if(result.isFlag()){
            String code = result.getData().toString();
            // 存入redis中,有效时间5分钟
            jedisPool.getResource().setex(telephone+ RedisConstant.SENDTYPE_ORDER,3000,code);
        }

        return result;
    }

    /**
     * 发送登录短信
     * @param telephone 手机号
     * @return
     */
    @PostMapping("/loginCode/{telephone}")
    public Result loginCode(@PathVariable("telephone") String telephone){

        // 匹配手机号
        String regExp="^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Matcher m = Pattern.compile(regExp).matcher(telephone);
        if(m.matches() == false){
            return new Result(false,"请输入正确的手机号码");
        }
        // 发送短信
        Result result =  result = SMSUtils.sendCodeByShortMessage(message.getHost(), message.getPath(), message.getAppcode(), message.getSkin(), telephone);

        // 取出验证码
        if(result.isFlag()){
            String code = result.getData().toString();
            System.out.println(code);
            // 存入redis中,有效时间5分钟
            jedisPool.getResource().setex(telephone+ RedisConstant.SENDTYPE_LOGIN,3000,code);
        }

        return result;
    }
}
